//
//  NGLocation.m
//  SudzCExamples
//
//  Created by Mehmet Sinan Şahin on 12/28/11.
//  Copyright 2011 netgis. All rights reserved.
//

#import "NGLocation.h"
#import "FTLocationSimulator.h"
#import "NGUtility.h"
#import "Status.h"
#import "NSDate+Extensions.h"
#import "StatusSpeedStrategyLastNLocations.h"
#import "RotatingNGLocation.h"


@implementation NGLocation

@synthesize deviceCode;
@synthesize tarihSaat;
@synthesize speed;
@synthesize lat;
@synthesize lon;
@synthesize status;
@synthesize date; //creation time of object
@synthesize sent;
@synthesize _id;
@synthesize strategy;

+(NGLocation *)initWithCLLocation:(CLLocation *)location {
    NGLocation *result = [[NGLocation alloc] autorelease];
    result.deviceCode = [NGUtility getDeviceId];
	result.lat = location.coordinate.latitude;
	result.lon = location.coordinate.longitude;
	result.speed = [[NSNumber numberWithDouble:location.speed] stringValue];
    result.tarihSaat = location.timestamp;
	result.status = UYGULAMA_ACILDI;
	result.date = [NSDate date]; //şimdiki zaman
    result.sent = FALSE;
    result.strategy = [[[StatusSpeedStrategyLastNLocations alloc] init] autorelease];
    return result;
}

-(void)calculateSpeedAndStatus: (RotatingNGLocation *) lastNLocations {
    float fSpeed = [strategy calculateSpeed:self rLocations:[lastNLocations retain]];
    self.speed = [[NSNumber numberWithFloat:fSpeed] stringValue];
    self.status = [strategy determineStatus:self rLocations:lastNLocations];
}


-(NSString *) description {
    NSString *statusMessage = @"";
    switch (status) {
        case HAREKET_EDIYOR:
            statusMessage = @"HAREKET_EDIYOR";
            break;
        case UYGULAMA_ACILDI:
            statusMessage = @"UYGULAMA_ACILDI";
            break;
        case UYGULAMA_KAPANDI:
            statusMessage = @"UYGULAMA_KAPANDI";
            break;
        case ALARM:
            statusMessage = @"ALARM";
            break;
        case DURDU:
            statusMessage = @"DURDU";
            break;
        case BEKLENMEYEN_KAPANIS:
            statusMessage = @"BEKLENMEYEN_KAPANIS";
            break;
        default:
            break;
    }
    return [NSString stringWithFormat:@"%@\r\n%@\nLat: %f\nLon: %f\nHız: %@\nDurum: %@ Sent: (%d)", [date toFormattedString], 
     [tarihSaat toFormattedString],
     lat,
     lon,
     speed,
     statusMessage, sent];    
}

-(BOOL)isEqualTo:(NGLocation *)loc {
    return [self.tarihSaat compare:loc.tarihSaat] == NSOrderedSame;
}

-(void)dealloc {
    [deviceCode release];
    [tarihSaat release];
    [speed release];
    [date release];
    [strategy release];
    [super dealloc];
}

@end
